import React, { useEffect, useState } from 'react';
import { ProForm, ProFormText, ProFormTextArea, ProFormSelect } from '@ant-design/pro-components';
import { Card, message } from 'antd';
import { useNavigate, useParams } from 'react-router-dom';
import api from '../../services/api';
import { Team, User } from '../../types';

const TeamForm: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [initialValues, setInitialValues] = useState<Partial<Team>>();
  const [users, setUsers] = useState<User[]>([]);
  const isEdit = !!id;

  useEffect(() => {
    fetchUsers();
    if (isEdit) {
      fetchTeam();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

  const fetchUsers = async () => {
    try {
      const response = await api.get('/users/', { params: { skip: 0, limit: 1000 } });
      // Handle both array and paginated response formats
      const usersData = Array.isArray(response.data) ? response.data : response.data.items || [];
      setUsers(usersData);
    } catch (error: any) {
      message.error('Failed to fetch users');
      setUsers([]); // Set empty array on error
    }
  };

  const fetchTeam = async () => {
    try {
      const response = await api.get(`/teams/${id}`);
      setInitialValues(response.data);
    } catch (error: any) {
      message.error('Failed to fetch team details');
      navigate('/teams');
    }
  };

  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      const payload = {
        ...values,
        team_admins: values.team_admins || [],
        team_members: values.team_members || [],
      };

      if (isEdit) {
        await api.put(`/teams/${id}`, payload);
        message.success('Team updated successfully');
      } else {
        await api.post('/teams/', payload);
        message.success('Team created successfully');
      }
      navigate('/teams');
    } catch (error: any) {
      message.error(error.response?.data?.detail || `Failed to ${isEdit ? 'update' : 'create'} team`);
    } finally {
      setLoading(false);
    }
  };

  const userOptions = (users || []).map((user) => ({
    label: `${user.username} (${user.email})`,
    value: user.id,
  }));

  return (
    <Card title={isEdit ? 'Edit Team' : 'Create Team'}>
      <ProForm
        initialValues={initialValues}
        onFinish={handleSubmit}
        loading={loading}
        submitter={{
          searchConfig: {
            submitText: isEdit ? 'Update' : 'Create',
          },
          resetButtonProps: {
            onClick: () => navigate('/teams'),
          },
        }}
      >
        <ProFormText
          name="name"
          label="Team Name"
          placeholder="Enter team name"
          rules={[{ required: true, message: 'Please enter team name' }]}
        />

        <ProFormTextArea
          name="description"
          label="Description"
          placeholder="Enter team description"
          fieldProps={{ rows: 4 }}
        />

        <ProFormSelect
          name="team_admins"
          label="Team Admins"
          mode="multiple"
          options={userOptions}
          placeholder="Select team admins"
          fieldProps={{
            showSearch: true,
            filterOption: (input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
          }}
        />

        <ProFormSelect
          name="team_members"
          label="Team Members"
          mode="multiple"
          options={userOptions}
          placeholder="Select team members"
          fieldProps={{
            showSearch: true,
            filterOption: (input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
          }}
        />
      </ProForm>
    </Card>
  );
};

export default TeamForm;
